package com.assignwork.service.impl;

import com.assignwork.entity.WorkArrangeAreas;
import com.assignwork.mapper.WorkArrangeAreasMapper;
import com.assignwork.service.IWorkArrangeAreasService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.utils.Func;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WorkArrangeAreasServiceImpl extends BaseServiceImpl<WorkArrangeAreasMapper, WorkArrangeAreas> implements IWorkArrangeAreasService {
    @Override
    public boolean submitWaAreas(Long arrangeId, String areaIds, String arrangeType) {
        boolean removeOldSuccess = removeByArrangeId(arrangeId);
        if (!Func.isNull(areaIds) && !Func.isBlank(areaIds)) {
            String[] areaIdList = areaIds.split(",");
            List<WorkArrangeAreas> areas = new ArrayList<>();
            for (String areaId : areaIdList) {
                WorkArrangeAreas newArea = new WorkArrangeAreas();
                newArea.setArrangeId(arrangeId);
                newArea.setAreaId(Func.toLong(areaId));
                newArea.setArrangeType(arrangeType);
                areas.add(newArea);
            }
            return removeOldSuccess && super.saveOrUpdateBatch(areas);
        } else {
            return removeOldSuccess;
        }
    }

    @Override
    public boolean removeByArrangeId(Long arrangeId) {
        QueryWrapper<WorkArrangeAreas> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .select(WorkArrangeAreas::getId)
                .eq(WorkArrangeAreas::getArrangeId,arrangeId)
                .eq(WorkArrangeAreas::getIsDeleted,0);
        List<WorkArrangeAreas> entities = baseMapper.selectList(queryWrapper);
        if (!Func.isEmpty(entities)) {
            List<Long> ids = entities.stream().map(WorkArrangeAreas::getId).collect(Collectors.toList());
            return super.deleteLogic(ids);
        }
        return true;
    }
}
